const { logger } = require("./log");
const crypto = require("./crypto");
const cors = require("cors"); //引入cors模块（解决跨域问题）
const cookieParser = require("cookie-parser");
const path = require("path");
const {
  message,
  requestLevel: { fail },
} = require("./message");
exports.requestMiddleware = (req, res, next) => {
  let params = {};
  switch (req.method) {
    case "GET":
    case "DELETE":
      params = req.query.params;
      break;
    case "POST":
    case "PUT":
    case "PATCH":
      params = req.body.params;
      break;
  }
  res.params = crypto.getCrypto(params);
  logger.info(res.params);
  next();
};
exports.setCors = (app) => {
  app.use(cors());
  app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "content-type"); //允许的header类型
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS"); //跨域允许的请求方式
    next(); //是否继续向下执行
  });
};
// 请求超时
exports.setReqTimeout = (app, t) => {
  app.use((_, res, next) => {
    res.setTimeout(t, () => {
      message({ res, type: fail, msg: "请求超时" });
      res.sendMsg && res.sendMsg();
    });
    next();
  });
};
exports.useCookieParser = (app) => {
  app.use(cookieParser());
};
exports.setPostConfig = (app, express) => {
  app.use(
    express.urlencoded({
      extended: false,
    })
  ); //bodyparser被弃用
  app.use(express.json());
};
exports.setStaticPath = (app, express, route, filePath) => {
  app.use(route, express.static(path.join(__dirname, filePath)));
};
